<script>
import axios from 'axios';
import { FileUtils } from '@/utils';

export default {
  props: {
    path: {
      type: String,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    async onDownload() {
      if (!this.path) {
        this.$message.warning('无可下载的文件');
        return;
      }

      // await FileUtils.download(this.path)
      // return

      try {
        const request = axios.create({
          responseType: 'blob', // 关键：指定响应类型为blob
          headers: {
            token: sessionStorage.getItem('authorization'),
          },
        });
        const response = await request.post(
          `/Api/FileDownload?path=${this.path}`
        );
        console.log('file download success');
        this.handleFileResponse(response);
      } catch (response) {
        console.log('file download err');
        if (response instanceof Blob) {
          this.handleFileResponse(response);
        } else {
        }
      }
    },
    handleFileResponse(response) {
      console.log(response, typeof response);
      // 从响应头获取文件名
      const contentDisposition = response.headers['content-disposition'];
      let fileName = 'downloadfile';

      if (contentDisposition) {
        // 解析文件名 (不同浏览器可能有不同格式)
        const match = contentDisposition.match(/filename="?(.+)"?/);
        if (match && match[1]) {
          fileName = decodeURIComponent(match[1]);
        }
      }

      // 创建blob对象
      const blob = new Blob([response.data]);

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.target = '_blank';
      a.download = fileName;

      // 模拟点击下载
      document.body.appendChild(a);
      a.click();

      // 清理资源
      setTimeout(() => {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, 100);
    },
  },
};
</script>

<template>
  <el-button
    type="text"
    icon="el-icon-download"
    size="mini"
    :disabled="!path || disabled"
    @click="onDownload()"
  >
    下载附件
  </el-button>
</template>

<style scoped lang="less"></style>
